package cn.cms.controller;


import cn.cms.model.SysUser;
import cn.cms.webcommon.ResBo;
import cn.cms.model.SysMenu;
import cn.cms.model.SysRole;
import cn.cms.service.SysMenuService;
import cn.cms.service.SysRoleService;

import cn.cms.util.ResponseUtil;
import cn.cms.util.SessionUtil;
import cn.cms.util.StringUtil;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping(value = "/sysrole")
public class SysRoleController extends AbstractController {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    SysMenuService sysMenuService;

    @RequestMapping("/page")
    public String page(HttpServletResponse response, Model model, String keyWord) {
        model.addAttribute("keyWord", keyWord);
        return "/sysrole/page";
    }

    @RequestMapping("/list")
    @ResponseBody
    public void list(HttpServletRequest request, HttpServletResponse response) {
        ResBo resBo = new ResBo();
        List<Integer> roleIds = new ArrayList<>();
        SysUser loginUser = SessionUtil.getUserSession(request);
        String[] roleIdss = ((loginUser.getRoleIds() == null) ? "" : loginUser.getRoleIds()).split(",");
        for (String roleId : roleIdss) {
            if (!StringUtil.isSpaceOrNull(roleId)) {
                roleIds.add(Integer.valueOf(roleId));
            }
        }
        // 当前登录用户角色最大级别
        int maxLevel = sysRoleService.getMaxLevel(roleIds);

        List<SysRole> sysRoles = sysRoleService.getRoles(maxLevel);// 位于登录用户角色级别相同或者级别更高的角色不允许该登录用户修改
        resBo.addResult("data", sysRoles);

        ResponseUtil.printAjaxPack(response, resBo);
    }

    @RequestMapping("/edit")
    public String edit(HttpServletResponse response, Model model, Integer id) {
        if (id != null) {
            SysRole sysRole = sysRoleService.getRoleById(id);
            model.addAttribute("sysRole", sysRole);
        }
        return "sysrole/form_tree";
    }

    @RequestMapping("/getMenus")
    public String getMenus(Model model, Integer id) {
        List<String> menuIds = new ArrayList<>();
        SysRole sysRole = sysRoleService.getRoleById(id);
        menuIds.addAll(Arrays.asList(((sysRole.getMenuIds() == null) ? "" : sysRole.getMenuIds()).split(",")));

        model.addAttribute("sysRole", sysRole);

        List<String> pMenuIds = null;
        SysRole pSysRole = sysRoleService.getRoleById(sysRole.getPid());
        if (pSysRole != null) {
            pMenuIds = new ArrayList<>();
            pMenuIds.addAll(Arrays.asList(((pSysRole.getMenuIds() == null) ? "" : pSysRole.getMenuIds()).split(",")));
        }
        List<SysMenu> sysMenus = sysMenuService.getMenus(menuIds, pMenuIds);
        // 清洗数据
        String menuIdstr = sysMenuService.getCheckedMenuIds(sysMenus);
        sysRole.setMenuIds(menuIdstr);
        model.addAttribute("menus_json", JSON.toJSON(sysMenus));
        return "sysrole/menus_tree";
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public void delete(HttpServletResponse response, SysRole sysRole) {
        ResBo resBo = new ResBo();
        if (sysRole.getId() != null) {
            sysRoleService.delete(sysRole);
        } else {
            resBo.setSuccess(false);
            resBo.setErrMsg("该项不存在或已经删除！");
        }
        ResponseUtil.printAjaxPack(response, resBo);
    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public void save(HttpServletResponse response, SysRole sysRole) {
        ResBo resBo = new ResBo();
        Date date = new Date();
        SysRole sysRoleSave;
        if (sysRole.getId() == null) {// 增加
            int pid = sysRole.getPid();
            // 父级节点级别
            int level = sysRoleService.getLevelById(pid);
            sysRoleSave = sysRole;
            // 父级节点级别+1
            sysRoleSave.setLevel(level + 1);
            sysRoleSave.setStatus(SysRole.STATUS_ENABLE);
            sysRoleSave.setCreateTime(date);
            sysRoleSave.setUpdateTime(date);
            int maxSort = sysRoleService.getMaxSort(sysRole.getPid());
            sysRoleSave.setSort(maxSort + 1);
            sysRoleService.save(sysRoleSave);
        } else {// 修改
            sysRoleSave = sysRoleService.getRoleById(sysRole.getId());
            sysRoleSave.setUpdateTime(date);
            sysRoleSave.setRoleName(sysRole.getRoleName());
            sysRoleSave.setSort(sysRole.getSort());
            sysRoleSave.setNote(sysRole.getNote());
            sysRoleService.update(sysRoleSave);
        }
        ResponseUtil.printAjaxPack(response, resBo);
    }

    @RequestMapping(value = "/saveMenus")
    @ResponseBody
    public void saveMenus(HttpServletResponse response, SysRole sysRole) {
        ResBo resBo = new ResBo();
        Date date = new Date();
        SysRole sysRoleSave;
        if (sysRole.getId() == null) {// 增加
            resBo.setSuccess(false);
            resBo.setErrMsg("角色不存在！");
        } else {// 修改
            sysRoleSave = sysRoleService.getRoleById(sysRole.getId());
            sysRoleSave.setUpdateTime(date);
            sysRoleSave.setMenuIds(sysRole.getMenuIds());
            sysRoleService.update(sysRoleSave);
        }
        ResponseUtil.printAjaxPack(response, resBo);
    }
}
